package bavaria.hightech.banking;

import java.util.Iterator;


public class ElementList<E> {
	
	private ListElement<E> first;
	private ListElement<E> counter;
	private int size;
	
	public ElementList(){
		first = null;
		counter = null;
		size = 0;
	}
	
	private ListElement<E> getLastPosition(){
		ListElement<E> help = first;
		if (help == null)
			return null;
		while(help.next != null){
			help = help.next;
		}
		return help; 
	}
	
	public boolean add(E element){	
		ListElement<E> newElement = new ListElement<E>(element);
		if(first == null)
			first = newElement;
		else {
			getLastPosition().next = newElement;
		}
		size++;
		return true;
	}
	
	public boolean clear(){
		first = null;
		size = 0;
		return true;
	}
	
	public E next(){	
		ListElement<E> help = counter;
		counter.next = counter.next.next;
		
		return help.get();
	}
	
	public String toString(){
		ListElement<E> help = first;
		StringBuffer buffer = new StringBuffer();
		if (help==null)
			return "Die Liste ist leer";
		while(help!=null){
			buffer.append(help.toString()+ "\n");
			help = help.next;
		}
		return buffer.toString();
	}
	
	public Iterator<E> iterator() {
		return new ListIterator();
	}

	private class ListIterator implements Iterator<E> {
		
		ListElement<E> cursor = first;

		public boolean hasNext() {
			
			return cursor.next!=null;
		}

		public E next() {
			if(hasNext()){
				ListElement<E> help = cursor;
				cursor = cursor.next;
				return help.get();
			}
			return null;
		}

		@Override
		public void remove() {
			cursor = null;
			
		}
		
	}
}

class ListElement <E>{
	
	private E element;
	public ListElement<E> next;
	
	public ListElement(E element){
		this.element = element;
	}
	
	public E get(){
		return element;
	}
	public String toString(){
		return element.toString();
	}
}



